<template>
  <div style="width: 100%;height: 100%">
    <mavon-editor v-model="value" @save="save" :toolbarsFlag="!readOnly" :defaultOpen="readOnly?'preview':'edit'" :ishljs = "true" :subfield="!readOnly"  :editable="!readOnly"
                  @imgAdd="imgAdd" ref="md"
    />
  </div>
</template>

<script>
  import {mavonEditor} from 'mavon-editor'
  import axios from 'axios'
  import 'mavon-editor/dist/css/index.css'
    export default {
        name: "GykjMarkDown",
      components:{
        mavonEditor
      },
      props:{
        markContent:{
          type: String,
          default: ""
        },
        alikey:{
          type: String,
          default: ""
        },
        alisecret:{
          type: String,
          default: ""
        },
        readOnly:{
          type: Boolean,
          default: false
        },
      },
      data () {
        return {
          value: "",
          token:null,
        }
      },
      mounted(){
        this.value=this.markContent;
        //非只读情况下需要认证
        if(!this.readOnly){
          axios.get(`https://api.agribigdata.com.cn/api-auth/api/v1/manager/auth/getSignature`, {
            params: {
              key: this.alikey||"",
              secret: this.alisecret|| "",
            }
          }).then(res =>{
            let sign=res.data;
            if (sign && sign.success) {
              this.token = sign.result;
            }else {
              this.value="key和secret认证失败"
            }
          }).catch(err=>{
            this.value="key和secret认证失败"
          });
        }

      },
      methods:{
        save(value,render){
          this.$emit("save",value,render);
        },
        imgAdd(pos,file){
          // 第一步.将图片上传到服务器.
          let formdata = new FormData();
          formdata.append('files', file);
          formdata.append('bucket', "freeww");
          formdata.append('accessKeyId', "oss9ccio3");
          formdata.append('accessKeySecret', "ms8m22w9");
          axios({
            url: 'https://api.agribigdata.com.cn/ossserver/api/v1/upload/uploadMaterials',
            method: 'post',
            data: formdata,
            headers: { 'Content-Type': 'multipart/form-data', "Signature":this.token},
          }).then(res => {
            // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
            /**
             * $vm 指为mavonEditor实例，可以通过如下两种方式获取
             * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
             * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
             */
            let url=res.data.data[0].url;
            console.log(this.$refs.md);
            this.$refs.md.$img2Url(pos, url);
          })
        }
      }
    }
</script>

<style scoped>

</style>
